package dream.web;

import com.alibaba.fastjson.JSON;
import dream.pojo.Article;
import dream.pojo.User;
import dream.service.ArticleService;
import dream.util.SessionUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.*;

@WebServlet("/myCollect")
public class MyCollectServlet extends HttpServlet {
    private ArticleService articleService = new ArticleService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = SessionUtils.getLoginUser(request);
        String cp = request.getParameter("cp");
        String ps = request.getParameter("ps");

        int j = (Integer.valueOf(cp)-1)*Integer.valueOf(ps);
        int length = Integer.valueOf(ps);

        List<Article> articles = new ArrayList<>();
        if(user == null){
            response.getWriter().write("");
            return;
        }else {
            int[] aids = articleService.SelectCollectById(user.getId());

            if(j >= aids.length){
                response.getWriter().write("");
                return;
            }
           for(int i = j; i < j + length; i++){
               if(i >= aids.length){
                   break;
               }
               Article article = articleService.SelectByAid(aids[i]);
               articles.add(article);
               System.out.println(article.getTitle());
           }
            // 转为JSON
            String jsonString = JSON.toJSONString(articles);

            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(jsonString);
        }
    }
}
